package oracletest;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) throws SQLException, ClassNotFoundException{
        List<Category> categories = buildCostCategoryTree();
        System.out.println("123");
    }

    /**
     * 存储结果集，封装成集合
     * @return
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public static List<Category> buildCostCategoryTree() throws SQLException, ClassNotFoundException {
        Connection con = Conrequest.quest();
        Statement statement = con.createStatement();
        List<Category> cateList = new ArrayList<>();
        String sql1 = "select ID,CATEGORY_NAME,PID,HAS_CHILD from COST_CATEGORY ";
        ResultSet resultSet1 = statement.executeQuery(sql1);
        while (resultSet1.next()){
            Category category = new Category(
                    resultSet1.getString("ID"),
                    resultSet1.getString("CATEGORY_NAME"),
                    resultSet1.getString("PID")
                    );
            cateList.add(category);
        }
        for (Category category : cateList) {
            List<Category> categories = new ArrayList<>();
            for (Category category1 : cateList) {
                if (category.getId().equals(category1.getPid())){
                    categories.add(category1);
                }
            }
            category.setChildren(categories);
        }
        buildCostCategoryTree2(cateList);
        return cateList;
    }

    /**拼接树
     *打印树结构1
     * @param cateList
     */
    public static void buildCostCategoryTree2(List<Category> cateList){
        for (Category category : cateList) {

            if (category.getPid().equals("0")){
                System.out.println(category.getName());
                if (category.getChildren().size()!=0){
                    buildCostCategoryTree3(cateList,category,2);
                }
            }
        }
    }

    /**
     * 打印树结构2
     * @param cateList
     * @param cate
     * @param i
     */
    public static void buildCostCategoryTree3(List<Category> cateList,Category cate,int i){
        for (Category category : cateList) {
            if (category.getPid().equals(cate.getId())){
                for (int j = 1; j <= i; j++) {
                    System.out.print(" ");
                }
                System.out.println(category.getName());
                if (category.getChildren().size()!=0){
                    buildCostCategoryTree3(cateList,category,i+2);
                }
            }
        }
    }
}
